import uuid
from datetime import datetime, timedelta
from uuid import uuid3

from sqlalchemy import extract

from models import db
from models.index import User, News, Category
from utils.qiniu import upload_qiniu
from views import admin_blu

from flask import render_template, request, jsonify, session, redirect, g


# 主页
@admin_blu.route("/admin")
def admin_index():
    user = g.user

    if user and g.user.is_admin:
        return render_template("admin/index.html", user=user)
    else:
        return redirect("/")


# 用户数量概况
@admin_blu.route("/user_count")
def user_count():
    # 查询用户总人数
    user_count = db.session.query(User).count()

    # 统计当月用户的新增数量
    now_date = datetime.now()  # datetime
    year = now_date.year
    month = now_date.month
    month_count = db.session.query(User).filter(extract('year', User.create_time) == year,
                                                extract('month', User.create_time) == month).count()

    # 统计当天用户的新增数量
    day = now_date.day
    day_count = db.session.query(User).filter(extract('year', User.create_time) == year,
                                              extract('month', User.create_time) == month,
                                              extract('day', User.create_time) == day).count()

    # 计算出近30天的数据
    counts_li = []
    date_li = []
    begin_date = now_date - timedelta(days=29)

    for i in range(0, 30):
        # 计算当前日期
        cur_date = begin_date + timedelta(days=i)

        # 获取当前日期的年月日
        year = cur_date.year
        month = cur_date.month
        day = cur_date.day

        # 计算出当天新增用户数量
        count = db.session.query(User).filter(extract('year', User.last_login) == year,
                                              extract('month', User.last_login) == month,
                                              extract('day', User.last_login) == day).count()

        # 把当天新增用户数量保存在counts_li列表中
        counts_li.append(count)

        # 保存当前日期
        date_str = cur_date.strftime('%Y-%m-%d')
        date_li.append(date_str)

        User_info = type("User_info", (),
                          {"month_count": month_count, "user_count": user_count, "day_count": day_count,
                           "counts_li": counts_li, "date_li": date_li})


    return render_template("admin/user_count.html", User_info=User_info)


# 用户列表
@admin_blu.route("/user_list.html")
def user_list():
    # 获取参数
    if g.user:
        page = request.args.get("page", 1)

        users = db.session.query(User).paginate(page=int(page), per_page=6, error_out=False)

        return render_template("admin/user_list.html", users=users)
    else:
        return redirect('/')


# 新闻详情
@admin_blu.route("/news_review.html")
def news_review():
    if g.user:
        page = request.args.get("page", 1)
        # 请求页数

        # 通过创建时间排序
        news_pag_pro = db.session.query(News).order_by(-News.create_time).paginate(page=int(page), per_page=6)

        return render_template("admin/news_review.html", news_pag_pro=news_pag_pro)
    else:
        return redirect('/')


# 新闻审核页面
@admin_blu.route("/news_review_detail.html")
def news_review_detail():
    # 获取参数 新闻id
    news_id = request.args.get("news_id")

    news = db.session.query(News).filter(News.id == news_id).first()

    return render_template("admin/news_review_detail.html", news=news)


# 新闻审核功能
@admin_blu.route("/news_review_detail/<int:news_id>", methods=["POST"])
def news_review_detail_fun(news_id):
    news = db.session.query(News).filter(News.id == news_id).first()
    if not news:
        # 如果没有id，那么就无需保存
        ret = {
            "errno": 5002,
            "errmsg": "没有对应的新闻"
        }
        return jsonify(ret)

    # 获取参数
    action = request.json.get("action")

    reason = request.json.get("reason")

    if action == "accept":
        news.status = 0
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "okok"
        }
    elif action == "reject":
        news.status = -1
        news.reason = reason
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "okok"
        }
    else:

        ret = {
            "errno": "0000",
            "errmsg": "?????"
        }

    return jsonify(ret)


@admin_blu.route("/news_edit.html")
def news_edit():
    page = request.args.get("page", 1)
    # 请求页数

    # 通过创建时间排序
    news_pag_pro = db.session.query(News).order_by(-News.create_time).paginate(page=int(page), per_page=6)

    return render_template("admin/news_edit.html", news_pag_pro=news_pag_pro)


# 新闻编辑页面
@admin_blu.route("/news_edit_detail.html")
def news_edit_detail():
    news_id = request.args.get("news_id")
    news = db.session.query(News).filter(News.id == news_id).first()

    # 所有分类
    categorys = db.session.query(Category).all()

    return render_template("admin/news_edit_detail.html", news=news, categorys=categorys)


# 新闻编辑功能
@admin_blu.route("/admin/news_edit_detail/<int:news_id>", methods=["POST"])
def save_news(news_id):
    # 更新新闻
    news = db.session.query(News).filter(News.id == news_id).first()
    if not news:
        # 如果没有id，那么就无需保存
        ret = {
            "errno": 5002,
            "errmsg": "没有对应的新闻"
        }
        return jsonify(ret)

    news.title = request.form.get("title")
    news.digest = request.form.get("digest")
    news.content = request.form.get("content")
    # 股市
    news.category_id = request.form.get("category_id")

    index_image_url = request.files.get("index_image_url")

    if index_image_url:
        # 获取文件后缀
        image_type = index_image_url.filename[index_image_url.filename.rfind("."):]

        index_image_url.filename = str(uuid3(uuid.NAMESPACE_URL, index_image_url.filename)) + image_type

        ret = upload_qiniu(index_image_url, index_image_url.filename)

        if ret:
            news.index_image_url = ret

    # 将修改的信息写入到数据库，此时真的更新成功
    db.session.commit()
    ret = {
        "errno": 0,
        "errmsg": "成功"
    }
    return jsonify(ret)


@admin_blu.route("/update_category", methods=['POST'])
def updete_category():
    # 获取数据
    id = request.json.get("id")
    cat_name = request.json.get("name")

    if id:

        car_pro = db.session.query(Category).filter(Category.id == id).first()

        car_pro.name = cat_name

        db.session.commit()

        ret = {
            "errno": 0,
            "errmsg": "okok"
        }

        return jsonify(ret)
    else:

        car_pro = Category(name=cat_name)

        db.session.add(car_pro)
        db.session.commit()

        ret = {
            "errno": 0,
            "errmsg": "okok"
        }

        return jsonify(ret)


@admin_blu.route("/news_type.html")
def news_type():
    category = db.session.query(Category).all()

    return render_template("admin/news_type.html", category=category)
